<script type="text/javascript">

    var rendererOptions = {
      draggable: true
    };
	var totalDistance = 0;
    var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    var directionsService = new google.maps.DirectionsService();
    var map;
    
    var srilanka = new google.maps.LatLng(7.0000, 81.0000);
	var orig = '';
	var dest = '';
	
	var data = {};
	var tempRoute = '';
    
    function initialize(origin, destination) {
    
	  orig = origin;
 	  dest = destination;
	  
      var mapOptions = {
        zoom: 8,
        center: srilanka
      };
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      directionsDisplay.setMap(map);
      directionsDisplay.setPanel(document.getElementById('directionsPanel'));
    
      google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
        computeTotalDistance(directionsDisplay.getDirections());
      });
  
      calcRoute();
    }
	
	function save_waypoints()
	{
		var w=[],wp;
		if (directionsDisplay.directions.routes[0].legs.length > 1) {
			var legFirst = directionsDisplay.directions.routes[0].legs[0];
			data.start = {'lat': legFirst.start_location.lat(), 'lng':legFirst.start_location.lng()}
			
			var legLast = directionsDisplay.directions.routes[0].legs[directionsDisplay.directions.routes[0].legs.length-1];
			data.end = {'lat': legLast.end_location.lat(), 'lng':legLast.end_location.lng()}
			//console.info("Length :" + directionsDisplay.directions.routes[0].legs.length);
			var tmpInt = 0;
			for(var i=0;i<directionsDisplay.directions.routes[0].legs.length;i++) {
				var rleg = directionsDisplay.directions.routes[0].legs[i];
				var tmpWp = rleg.via_waypoints;
				if (tmpWp.length>0) {
					if(wp!=null){
						wp.push(tmpWp);
					} else {
						wp = rleg.via_waypoints;
					}
				}
				if (i!=directionsDisplay.directions.routes[0].legs.length-1) {
					w[i] = [rleg.end_location.lat(),rleg.end_location.lng()];
				}
			}
			if(wp!=null){
				var currWPLen = w.length;
				for(var i=0;i<wp.length;i++) {
					w[currWPLen] = [wp[i].lat(),wp[i].lng()];
					currWPLen++;
				}
			}
			//console.info("Full WP: " + w);
			data.waypoints = w;
			
		} else {
			var rleg = directionsDisplay.directions.routes[0].legs[0];
			data.start = {'lat': rleg.start_location.lat(), 'lng':rleg.start_location.lng()}
			data.end = {'lat': rleg.end_location.lat(), 'lng':rleg.end_location.lng()}
			var wp = rleg.via_waypoints
			for(var i=0;i<wp.length;i++)w[i] = [wp[i].lat(),wp[i].lng()]
			data.waypoints = w;
		}
		 
		tempRoute = JSON.stringify(data);
		//console.info(tempRoute);
	}
	
	function loadSavedRoute()
	{	
		var os = eval('(' + tempRoute + ')');
		var wp = [];
		for(var i=0;i<os.waypoints.length;i++)
			wp[i] = {'location': new google.maps.LatLng(os.waypoints[i][0], os.waypoints[i][1]),'stopover':true }
			 
		directionsService.route({'origin':new google.maps.LatLng(os.start.lat,os.start.lng),
		'destination':new google.maps.LatLng(os.end.lat,os.end.lng),
		'waypoints': wp,
		'optimizeWaypoints': true,
		'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
			if(sts=='OK')directionsDisplay.setDirections(res);
		}) 
	}
	
    function calcRoute() {
      var request = {
        origin: orig,
        destination: dest,
        travelMode: google.maps.TravelMode.DRIVING
      };
      directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
        }
      });
    }
    
    function computeTotalDistance(result) {
      var myroute = result.routes[0];
      for (var i = 0; i < myroute.legs.length; i++) {
        totalDistance += myroute.legs[i].distance.value;
      }
      totalDistance = totalDistance / 1000.
      document.getElementById('totalDistance').innerHTML = totalDistance + ' km';
	  var approxDistance =  Math.round(totalDistance * 100) / 100 ;
	  $( ".distance" ).val(approxDistance);
    }
    
    //google.maps.event.addDomListener(window, 'load', initialize);
    
</script>
<div id="map-canvas" style="width:100%; height:400px;"></div>
<div id="directions" style="width:100%; height:400px; overflow:auto;">
    <div id="directionsPanel">
        <p>Total Distance: <span id="totalDistance"></span></p>
    </div>
</div>
<div style="width:100%;height:50px; float:left">
	<div id="div-show-directions" style="float:left;"><input type="button" id="show-directions" value="Show Directions"/></div>
    <div id="div-hide-directions" style="float:left;"><input type="button" id="hide-directions" value="Hide Directions"/></div>
</div>

<script>
    $(function(){
        $("#directions").hide();
		$("#div-hide-directions").hide();
    });
    
    $("#show-directions").bind('click', function(){
        $("#directions").show();
		$("#map-canvas").hide();
		$("#route-controls").hide();
		$("#div-hide-directions").show();
		$("#div-show-directions").hide();
    });
    
    $("#hide-directions").bind('click', function(){
        $("#directions").hide();
		$("#map-canvas").show();
		$("#route-controls").show();
		$("#div-hide-directions").hide();
		$("#div-show-directions").show();
		
    });
</script>